package org.kl.auditsupervision.service.fnd;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.ExcelImportFile;
import org.kl.bf.entity.basic.User;
import org.kl.bf.entity.easyui.Json;
import org.kl.bf.repository.basic.ExcelImportFileDao;
import org.kl.bf.repository.basic.UserDao;
import org.kl.bf.service.BasicService;
import org.kl.bf.service.ExcelImportLogger;
import org.kl.bf.service.ServiceException;
import org.kl.bf.utils.ExcelReader;
import org.kl.bf.web.base.BasicController;
import org.kl.auditsupervision.entity.fnd.Employee;
import org.kl.auditsupervision.repository.fnd.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Collections3;
import org.springside.modules.utils.Encodes;

import com.alibaba.fastjson.JSON;
/**
 * @author Code Generator
 * @since  2015-09-09 10:59:55
 * @see 人员信息表  人员信息表
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class EmployeeService extends BasicService<Employee> {
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;
	
	@Autowired
	private ExcelImportFileDao excelImportFileDao;
	@Autowired
	private ExcelImportLogger excelImportLogger;
	@Autowired
	private EmployeeDao employeeDao;  
	@Autowired
	private UserDao userDao;
	
	public void save(Employee entity, @RequestParam(value = "inserted") String detailInserted,
			@RequestParam(value = "updated") String detailUpdated, @RequestParam(value = "deleted") String detailDeleted) {
		employeeDao.save(entity);
		if (StringUtils.isNotBlank(detailInserted)) {
			List<Employee> inserts = JSON.parseArray(detailInserted, Employee.class);
			if (Collections3.isNotEmpty(inserts)) {
				for (Employee a : inserts) {
					// 增加与主表相关的数据复制代码
					employeeDao.save(a);
				}
			}
		}
		if (StringUtils.isNotBlank(detailUpdated)) {
			List<Employee> updates = JSON.parseArray(detailUpdated, Employee.class);
			if (Collections3.isNotEmpty(updates)) {
				for (Employee b : updates) {
					employeeDao.save(b);
				}
			}
		}
		if (StringUtils.isNotBlank(detailDeleted)) {
			List<Employee> deletes = JSON.parseArray(detailDeleted, Employee.class);
			if (Collections3.isNotEmpty(deletes)) {
				employeeDao.delete(deletes);
			}
		}
	}
	
	/*
	 * 分配登陆账号
	 * */
	
	public String fpUser(String ids) {
		String[] idArray = StringUtils.split(ids, ",");
		int i = 0, j = 0;
		for (String id : idArray) {
			if (StringUtils.isNotBlank(id)) {
				//User u = userDao.findByEmployeeId(id);
				List<User>  userList= userDao.findByEmployeeId(id);
				if (userList.size()<=0) {
					//staffinfoDao.delete(id);
					User user = new User();
					Employee staffinfo = employeeDao.findOne(id);
					user.setTrueName(staffinfo.getTrueName());
					user.setLoginNo(staffinfo.getJobNumber());
					user.setPlainPassword(staffinfo.getJobNumber());
					user.setEmployee(staffinfo);
					user.setUserType("员工");
					entryptPassword(user);
					userDao.save(user);
					i++;
				} else {
					j++;
				}
			}
		}
		return "成功分配" + i + "个账号,已分配" + j + "各登陆账号";
	}
	
	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(user.getPlainPassword().getBytes(), salt, HASH_INTERATIONS);
		user.setPassword(Encodes.encodeHex(hashPassword));
	}

	public List<Employee> findByTrueName(String trueName) {
		return employeeDao.findByTrueName(trueName);
	}

	public int importExcel(String importNo, String excelImportFileId) {
		int success=0;
		ExcelImportFile a = excelImportFileDao.findOne(excelImportFileId);
		List<String[]> excelData = new ExcelReader(a.getFilePath()).getAllData(0);
		if (Collections3.isEmpty(excelData)) {
			String msg = "导入文件内容为空";
			excelImportLogger.log("ExcelConfig", ExcelImportLogger.LoggerAction.FORMET_CHECKS.getActionName(),
					BasicController.getCurrentUserName(), new Json(msg));
			throw new ServiceException(msg);
		}else{
			success = importDBFromExcel(excelData);
		}
		return success;
	}
	
	/**
	 * 将Excel数据插入或者更新数据库
	 * 
	 * @param excelData
	 * @return 字符串，包含用逗号隔开的多个值{重名数，重名姓名1，重名姓名2，...，找不到姓名1，找不到姓名2，...}
	 */
	public int importDBFromExcel(List<String[]> excelData) {
		int add=0;
		for (int i = 0; i < excelData.size(); i++) {
			String employeeId = getDataFromDB(excelData.get(i));
			Employee employee = employeeDao.findOne(employeeId);
			//employee.setSalarySerialNo(excelData.get(i)[1]);
			employeeDao.save(employee);
			add++;
		}
		return add;
	}
	
	/**
	 * 获取Excel数据，对关联值处理找到其表的主键ID
	 * 
	 * @param rowData  行数据
	 * @return 关联数据主键id
	 * @throws ServiceException
	 */
	private String getDataFromDB( String[] rowData) throws ServiceException {	
		// 下面这段是为了判断数据是否完整
		List<Employee> result = new ArrayList<Employee>();
		if(rowData.length<2){
			throw new ServiceException("教师["+rowData[0]+"]Excel导入配置中关联字段集与需求值个数不匹配!");
		}else{
			result = employeeDao.findByTrueName(rowData[0]);			
		}
		if (result.size()!=1) {
			throw new ServiceException("教师["+rowData[0]+"]重名或无记录！");
		}
		return result.get(0).getId();
	}
}
